package cn.com.doone.common.uc.oauth.authorize;

import cn.com.doone.common.uc.domain.oauth.ClientDetails;
import cn.com.doone.common.uc.oauth.OAuthAuthxRequest;
import cn.com.doone.common.uc.oauth.validator.AbstractClientDetailsValidator;
import cn.com.doone.common.uc.oauth.validator.CodeClientDetailsValidator;
import cn.com.doone.common.uc.utils.HttpClientUtil;
import cn.com.doone.common.uc.utils.StringUtils;
import cn.com.doone.common.uc.web.WebUtils;

import org.apache.oltu.oauth2.as.response.OAuthASResponse;
import org.apache.oltu.oauth2.common.exception.OAuthSystemException;
import org.apache.oltu.oauth2.common.message.OAuthResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * 2015/6/25
 * <p/>
 * Handle response_type = 'code'
 *
 * @author Shengzhao Li
 */
public class CodeAuthorizeHandler extends AbstractAuthorizeHandler {

	private static final Logger LOG = LoggerFactory.getLogger(CodeAuthorizeHandler.class);

	public CodeAuthorizeHandler(OAuthAuthxRequest oauthRequest, HttpServletResponse response) {
		super(oauthRequest, response);
	}

	@Override
	protected AbstractClientDetailsValidator getValidator() {
		return new CodeClientDetailsValidator(oauthRequest);
	}

	// response code
	@Override
	protected void handleResponse() throws OAuthSystemException, IOException {
		final ClientDetails clientDetails = clientDetails();
		final String authCode = oauthService.retrieveAuthCode(clientDetails);
		// 判断通过什么渠道登陆
		String loginType = StringUtils.isNull(oauthRequest.getParam("appCode")) ? "WEB"
				: oauthRequest.getParam("appCode");
		//取数据库回跳地址
		String locationUri = HttpClientUtil
				.decodeURIComponent(HttpClientUtil.decodeURIComponent(oauthRequest.getRedirectURI()));
		LOG.debug("传递登录地址是:"+locationUri+",数据库地址是:"+clientDetails.getRedirectUri());
		//如果数据库中为https协议，则把url的http转为https
		if(clientDetails.getRedirectUri().startsWith("https://") && locationUri.startsWith("http://")) {
			locationUri = locationUri.replaceFirst("http", "https");
		}
//		locationUri = HttpClientUtil.encodeURIComponent(HttpClientUtil.encodeURIComponent(locationUri));
		LOG.debug("重定向地址是:"+locationUri);
		final OAuthResponse oAuthResponse = OAuthASResponse
				.authorizationResponse(oauthRequest.request(), HttpServletResponse.SC_OK)
				// .location(clientDetails.getRedirectUri())
				.location(locationUri).setCode(authCode).buildQueryMessage();

		//写app日志
		Map<String,Object> loggerMap = new HashMap<String,Object>();
		loggerMap.put("login_account", this.getUserInfo().get("USER_ACCOUNT"));
		loggerMap.put("login_type", loginType);
		loggerMap.put("login_app", clientId());
		loggerMap.put("is_success", true);
		loggerMap.put("reason", 0);
		LOG.info(loggerMap.toString());
		
		WebUtils.writeOAuthQueryResponse(response, oAuthResponse);
	}
}
